# curve_combobox_coords.py
import tkinter as tk
from tkinter import ttk
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from scipy.interpolate import CubicSpline
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# ---------- 中文显示 ----------
matplotlib.rcParams['font.family'] = 'SimHei'
matplotlib.rcParams['axes.unicode_minus'] = False

# ---------- 主窗口 ----------
root = tk.Tk()
root.title("曲线显示（组合单选框+坐标标注）")
root.geometry("640x540")

# ---------- 变量 ----------
curve_mode = tk.StringVar(value="折线")
coords_visible = False   # 标注开关
x_data, y_data = None, None   # 保存最新数据，供标注使用

# ---------- 绘图函数 ----------
def draw_plot(*args):
    global x_data, y_data
    ax.clear()
    ax.set_title("随机序列曲线显示")
    ax.set_xlabel("索引")
    ax.set_ylabel("值")

    x_data = np.arange(16)
    y_data = np.random.randint(0, 100, size=16)
    mode = curve_mode.get()

    if mode == "折线":
        ax.plot(x_data, y_data, marker='o', label='折线')
    elif mode == "三次样条":
        cs = CubicSpline(x_data, y_data)
        x_new = np.linspace(0, 15, 300)
        y_new = cs(x_new)
        ax.plot(x_new, y_new, label='三次样条曲线')
        ax.plot(x_data, y_data, 'o', color='gray', markersize=4)

    ax.legend()
    toggle_coords(False)   # 切换曲线时重置标注
    canvas.draw()

# ---------- 坐标标注 ----------
def toggle_coords(force=None):
    global coords_visible
    if force is not None:
        coords_visible = force
    else:
        coords_visible = not coords_visible

    # 移除旧标注
    for ann in coord_ann:
        ann.remove()
    coord_ann.clear()

    if coords_visible and x_data is not None:
        for x, y in zip(x_data, y_data):
            ann = ax.annotate(f'({x},{y})', (x, y),
                              textcoords="offset points",
                              xytext=(0, 10), ha='center', fontsize=8, color='darkred')
            coord_ann.append(ann)
    canvas.draw()

coord_ann = []   # 保存当前标注对象

# ---------- 控件 ----------
ctrl_frame = ttk.Frame(root)
ctrl_frame.pack(pady=10)

ttk.Label(ctrl_frame, text="曲线类型：").pack(side="left")
mode_combo = ttk.Combobox(ctrl_frame, textvariable=curve_mode,
                          values=["折线", "三次样条"], state="readonly", width=12)
mode_combo.pack(side="left", padx=10)
mode_combo.bind("<<ComboboxSelected>>", draw_plot)

ttk.Button(ctrl_frame, text="显示坐标", command=toggle_coords).pack(side="left", padx=15)

# ---------- 图形区域 ----------
fig, ax = plt.subplots(figsize=(6, 4))
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack()

# ---------- 初始绘制 ----------
draw_plot()

# ---------- 主循环 ----------
root.mainloop()